package com.rfid.web.controller.system;

import java.text.CollationElementIterator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.rfid.common.constant.Constants;
import com.rfid.common.exception.BusinessException;
import com.rfid.common.utils.ShiroUtils;
import com.rfid.common.utils.StringUtils;
import com.rfid.framework.web.domain.server.Sys;
import com.rfid.system.domain.TProductInfo;
import com.rfid.system.domain.TRfidDataDetail;
import com.rfid.system.service.ISysConfigService;
import com.rfid.system.service.ITProductInfoService;
import com.rfid.system.service.ITRfidDataDetailService;
import com.rfid.system.service.common.DictRfidService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rfid.common.annotation.Log;
import com.rfid.common.enums.BusinessType;
import com.rfid.system.domain.TItemInfo;
import com.rfid.system.service.ITIteminfoService;
import com.rfid.common.core.controller.BaseController;
import com.rfid.common.core.domain.AjaxResult;
import com.rfid.common.utils.poi.ExcelUtil;
import com.rfid.common.core.page.TableDataInfo;

/**
 * 成品管理
 *
 * @author ruoyi
 * @date 2020-11-27
 */
@Controller
@RequestMapping("/system/iteminfo")
public class TIteminfoController extends BaseController {
    private String prefix = "system/iteminfo";

    @Autowired
    private ITIteminfoService tIteminfoService;

    @Autowired
    private ITProductInfoService iTProductInfoService;

    @Autowired
    private ISysConfigService iSysConfigService;

    @Autowired
    private ITRfidDataDetailService tRfidDataDetailService;


    @Autowired
    private DictRfidService dictRfidService;



    @RequiresPermissions("system:iteminfo:view")
    @GetMapping()
    public String iteminfo() {
        return prefix + "/iteminfo";
    }

    /**
     * 查询成品列表
     */
    @RequiresPermissions("system:iteminfo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TItemInfo tIteminfo) {
        startPage();
        List<TItemInfo> list = tIteminfoService.selectTIteminfoList(tIteminfo);
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(item->{
               String productId=item.getProductInfoId();
                TProductInfo tProductInfo=iTProductInfoService.selectTProductInfoById(Long.valueOf(productId));
                if(tProductInfo!=null){
                    item.setProductName(tProductInfo.getProductName());
                }
            });
        }
        if(StringUtils.isNotEmpty(tIteminfo.getProductName())){
            list=list.stream().filter(item->item.getProductName().equals(tIteminfo.getProductName())).collect(Collectors.toList());
        }
        return getDataTable(list);
    }

    /**
     * 导出成品列表
     */
    @RequiresPermissions("system:iteminfo:export")
    @Log(title = "成品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TItemInfo tIteminfo) {
        List<TItemInfo> list = tIteminfoService.selectTIteminfoList(tIteminfo);
        ExcelUtil<TItemInfo> util = new ExcelUtil<TItemInfo>(TItemInfo.class);
        return util.exportExcel(list, "iteminfo");
    }

    /**
     * 新增成品
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存成品
     */
    @RequiresPermissions("system:iteminfo:add")
    @Log(title = "成品", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TItemInfo tIteminfo) {
        //成品表序列号长度
        String ITEM_CODE_LENGTH=iSysConfigService.selectConfigByKey("ITEM_CODE_LENGTH");
        TProductInfo tProductInfo=new TProductInfo();
        tProductInfo.setId(Long.valueOf(tIteminfo.getProductInfoId()));
        TProductInfo productInfo=iTProductInfoService.selectTProductInfoById(Long.valueOf(tIteminfo.getProductInfoId()));
        if(productInfo==null){
            throw new BusinessException("产品信息不存在");
        }
        String productNo=productInfo.getProductNo();
        if(tIteminfo.getProductNum()==0){
            throw new BusinessException("输入的成品数量必须大于0");
        }
        for(int i=0;i<tIteminfo.getProductNum();i++){
            //获取对应产品编号的最后一条记录
            TItemInfo info=new TItemInfo();
            info.setItemNo(productNo);
            TItemInfo item=tIteminfoService.getLastData(info);
            //生成单品号
            String itemNo="";
            //序列号
            Integer series=null;
            if(item!=null){
                System.out.println(item.getItemNo().substring(0,productNo.length()));
                series=Integer.valueOf(item.getItemNo().replace(item.getItemNo().substring(0,productNo.length()),""));
                series++;
                itemNo=String.valueOf(series);
                for(int j=0;itemNo.length()<Integer.valueOf(ITEM_CODE_LENGTH);j++){
                    itemNo="0"+itemNo;
                }
                itemNo=productNo+itemNo;

            }else{
                String zero=Constants.PREFIX_ZERO;
                String itemNoSuffix=zero.substring(0,Integer.valueOf(ITEM_CODE_LENGTH)-1);
                itemNo=productNo+itemNoSuffix+"1";
            }
            tIteminfo.setItemNo(itemNo);
            tIteminfo.setCreateBy(ShiroUtils.getLoginName());
            tIteminfo.setCreateTime(new Date());
            tIteminfo.setUpdateBy(ShiroUtils.getLoginName());
            tIteminfo.setUpdateTime(new Date());
            tIteminfo.setField(productInfo.getProductNo());
            tIteminfoService.insertTIteminfo(tIteminfo);
        }

        return AjaxResult.success(tIteminfo.getProductNum());
    }

    /**
     * 修改成品
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        TItemInfo tIteminfo = tIteminfoService.selectTIteminfoById(id);
        mmap.put("tIteminfo", tIteminfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存成品
     */
    @RequiresPermissions("system:iteminfo:edit")
    @Log(title = "成品", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TItemInfo tIteminfo) {
        TProductInfo productInfo=iTProductInfoService.selectTProductInfoById(Long.valueOf(tIteminfo.getProductInfoId()));
        if(productInfo==null){
            throw new BusinessException("产品信息不存在");
        }
        tIteminfo.setField(productInfo.getProductNo());
        return toAjax(tIteminfoService.updateTIteminfo(tIteminfo));
    }

    /**
     * 删除成品
     */
    @RequiresPermissions("system:iteminfo:remove")
    @Log(title = "成品", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(tIteminfoService.deleteTIteminfoByIds(ids));
    }


    /**
     * @Author fangchen
     * @Description //查看成品详情
     * @Date 16:41 2020/12/16
     * @Param [itemId, mmap]
     * @return java.lang.String
     **/
    @RequiresPermissions("system:product:detail")
    @GetMapping("/detail/{itemId}")
    public String detail(@PathVariable("itemId") Long itemId, ModelMap mmap) {
        TItemInfo tIteminfo = tIteminfoService.selectTIteminfoById(itemId);
        String productId=tIteminfo.getProductInfoId();
        TProductInfo tProductInfo=iTProductInfoService.selectTProductInfoById(Long.valueOf(productId));
        if(tProductInfo!=null){
            tIteminfo.setProductName(tProductInfo.getProductName());
        }
        mmap.put("tIteminfo", tIteminfo);
        return prefix + "/detail";
    };

    @RequiresPermissions("system:product:detail")
    @GetMapping("/rfiddetail/{itemId}")
    public String rfiddetail(@PathVariable("itemId") Long itemId, ModelMap mmap) {
        TItemInfo tIteminfo = tIteminfoService.selectTIteminfoById(itemId);
        String productId=tIteminfo.getProductInfoId();
        TProductInfo tProductInfo=iTProductInfoService.selectTProductInfoById(Long.valueOf(productId));
        if(tProductInfo!=null){
            tIteminfo.setProductName(tProductInfo.getProductName());
        }
        mmap.put("tIteminfo", tIteminfo);
        return prefix + "/rfiidDetail";
    }


    @RequiresPermissions("system:iteminfo:list")
    @PostMapping("/rfidlist")
    @ResponseBody
    public TableDataInfo rfidlist(String  itemNo) {
        startPage();
        TRfidDataDetail tRfidDataDetail=new TRfidDataDetail();
        tRfidDataDetail.setItemNo(itemNo);
        List<TRfidDataDetail> list = tRfidDataDetailService.selectTRfidDataDetailList(tRfidDataDetail);
        list.stream().forEach(detail->{
            detail.setFuncName(dictRfidService.getLabelByCode("RFID_FUNCTION",detail.getFuncId()+""));
        });
        if(StringUtils.isNotEmpty(tRfidDataDetail.getProductName())){
            String productName=tRfidDataDetail.getProductName();
            list=list.stream().filter(detail->productName.equals(detail.getProductName())).collect(Collectors.toList());
        }
        if(tRfidDataDetail.getFuncId()!=null){
            String funcName=dictRfidService.getLabelByCode("RFID_FUNCTION",tRfidDataDetail.getFuncId()+"");
            list=list.stream().filter(detail->funcName.equals(detail.getFuncName())).collect(Collectors.toList());
        }
        return getDataTable(list);
    }

}
